
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jhtoast/jhtoast.dart';
import 'package:photo_manager/photo_manager.dart';
import '../../../generated/r_images.dart';
import '../../widgets/app_image.dart';
import '../../widgets/common_button.dart';
import 'keep_alive_wrapper.dart';
import 'package:photo_manager_image_provider/photo_manager_image_provider.dart';
import 'asset_controller.dart';

class VolvoAssetPreviewPage extends StatefulWidget {
  final List<AssetModel> dataList;
  final List<AssetModel>? selectedAssets;
  final int currentIndex;
  final int maxAssetCount;
  final int maxVideoLength;
  final ValueChanged<List<AssetModel>>? selectedCallback;

  const VolvoAssetPreviewPage({
    super.key,
    required this.dataList,
    this.selectedAssets,
    this.currentIndex = 0,
    this.maxAssetCount = 1,
    this.maxVideoLength = 15,
    this.selectedCallback,
  });

  @override
  State<VolvoAssetPreviewPage> createState() => _VolvoAssetPreviewPageState();
}

class _VolvoAssetPreviewPageState extends State<VolvoAssetPreviewPage> {
  late VolvoAssetPreviewController _previewController;

  @override
  void initState() {
    super.initState();
    _previewController = VolvoAssetPreviewController(
      dList: widget.dataList,
      sAssets: widget.selectedAssets,
      cIndex: widget.currentIndex,
      maxAssetCount: widget.maxAssetCount,
      maxVideoLength: widget.maxVideoLength,
      callback: widget.selectedCallback,
    );
  }

  @override
  void dispose() {
    _previewController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: widget.dataList.isEmpty ? const SizedBox() : _buildContent(),
    );
  }

  /// 内容
  Widget _buildContent() {
    return Container(
      color: Colors.black,
      child: Column(
        children: [
          _buildTop(),
          Expanded(child: _buildPageView()),
          _buildSelectedImage(),
          _buildComplete(),
        ],
      ),
    );
  }

  /// 顶部
  Widget _buildTop() {
    return Container(
      padding: EdgeInsets.only(
          top: MediaQuery.of(context).padding.top, left: 16, right: 16),
      height: kToolbarHeight + MediaQuery.of(context).padding.top,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            child: Container(
              alignment: Alignment.centerLeft,
              child: AppImage.assets(AppR.back,
                width: 24.r,
                height: 24.r,
              ),
            ),
            onTap: () {
              Navigator.pop(context, _previewController.selectedAssets);
            },
          ),
          _buildState(),
        ],
      ),
    );
  }

  /// 选择状态
  Widget _buildState() {
    return AnimatedBuilder(
      animation: _previewController,
      builder: (BuildContext ctx, Widget? child) {
        bool isSelected = _previewController.currentAssetModel.isSelected;
        Widget selectImage = AppImage.assets(AppR.update_success,
          width: 44.r,
          height: 44.r,
        );
        if(isSelected == false){
          selectImage = AppImage.colorImage(selectImage, Colors.grey);
        }
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          child: SizedBox(
            width: 44.r,
            height: 44.r,
            child: Align(
              alignment: Alignment.centerRight,
              child: selectImage
            ),
          ),
          onTap: () {
            _previewController.clickAsset(context);
          },
        );
      },
    );
  }

  /// 资源Page
  Widget _buildPageView() {
    return Container(
      color: Colors.black,
      child: PageView.builder(
        controller: _previewController.pageController,
        itemCount: _previewController.dataList.length,
        itemBuilder: (context, index) {
          AssetModel model = _previewController.dataList[index];
          return KeepAliveWrapper(child: _buildImage(model));
        },
        onPageChanged: (value) {
          _previewController.changeAsset(value);
        },
      ),
    );
  }

  /// 资源图片
  Widget _buildImage(AssetModel model) {
    return AssetEntityImage(
      model.assetEntity,
      isOriginal: true,
      fit: BoxFit.contain,
      thumbnailSize: ThumbnailSize.square(80),
    );
  }

  /// 已选中的图片
  Widget _buildSelectedImage() {
    return AnimatedBuilder(
      animation: _previewController,
      builder: (BuildContext context, Widget? child) {
        return _previewController.selectedAssets.isEmpty
            ? const SizedBox()
            : Padding(
                padding: const EdgeInsets.only(top: 16, left: 16),
                child: Stack(
                  children: [
                    IgnorePointer(
                      child: Opacity(
                        opacity: 0.0,
                        child: _buildSelectedImageItem(0),
                      ),
                    ),
                    const SizedBox(width: double.infinity),
                    Positioned.fill(
                      child: ListView.separated(
                        padding: EdgeInsets.zero,
                        scrollDirection: Axis.horizontal,
                        itemCount: _previewController.selectedAssets.length,
                        itemBuilder: (BuildContext context, int index) {
                          return _buildSelectedImageItem(index);
                        },
                        separatorBuilder: (BuildContext context, int index) {
                          return const SizedBox(width: 8);
                        },
                      ),
                    ),
                  ],
                ),
              );
      },
    );
  }

  /// 已选中的图片Item
  Widget _buildSelectedImageItem(int index) {
    AssetModel selectedModel = _previewController.selectedAssets[index];
    String selectedID = selectedModel.assetEntity.id;
    String currentID = _previewController.currentAssetModel.assetEntity.id;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        width: 56,
        height: 56,
        color: Colors.white,
        padding: selectedID == currentID
            ? const EdgeInsets.all(2.33)
            : EdgeInsets.zero,
        child:
        AssetEntityImage(
          selectedModel.assetEntity,
          isOriginal: false,
          fit: BoxFit.cover,
          thumbnailSize: const ThumbnailSize.square(80),
        ),
      ),
      onTap: () {
        _previewController.clickSelectedAsset(selectedModel);
      },
    );
  }

  /// 完成
  Widget _buildComplete() {
    return AnimatedBuilder(
      animation: _previewController,
      builder: (BuildContext context, Widget? child) {
        return Padding(
          padding: EdgeInsets.only(
              top: 16,
              left: 16,
              right: 16,
              bottom: MediaQuery.of(context).padding.bottom + 16),
          child: CommonButton(text:_previewController.selectedAssets.isEmpty
              ? '完成'
              : "完成(${_previewController.selectedAssets.length}/${widget.maxAssetCount})",
            onPressed: () {
              _previewController.complete(context);
            },
          )
        );
      },
    );
  }
}

class VolvoAssetPreviewController extends ChangeNotifier {
  late PageController pageController;

  /// 总资源
  List<AssetModel> dataList = [];

  /// 已选中的资源
  List<AssetModel> selectedAssets = [];

  /// 当前资源
  late AssetModel currentAssetModel;

  /// 当前索引
  late int currentIndex;

  /// 资源选择的最大数量
  late int _maxAssetCount;

  /// 视频最大长度
  late int _maxVideoLength;

  /// 资源选择回调
  ValueChanged<List<AssetModel>>? _selectedCallback;

  VolvoAssetPreviewController({
    required List<AssetModel> dList,
    List<AssetModel>? sAssets,
    int cIndex = 0,
    int maxAssetCount = 1,
    int maxVideoLength = 15,
    ValueChanged<List<AssetModel>>? callback,
  }) {
    _maxAssetCount = maxAssetCount;
    _maxVideoLength = maxVideoLength;
    _selectedCallback = callback;
    currentIndex = cIndex;
    pageController = PageController(initialPage: currentIndex);

    /// 数据处理
    if (dList.isNotEmpty) {
      // List<AssetModel> tempDataList = [];
      // for (AssetModel model in dList) {
      //   AssetModel tempModel = model.copyWith();
      //   tempDataList.add(tempModel);
      // }
      //
      // List<AssetModel> tempSelectedAssets = [];
      // if (sAssets != null) {
      //   for (AssetModel model in sAssets) {
      //     AssetModel tempModel = model.copyWith();
      //     tempSelectedAssets.add(tempModel);
      //   }
      // }

      dataList.addAll(dList);
      selectedAssets.addAll(sAssets ?? []);
      currentAssetModel = currentIndex > dataList.length
          ? dataList.first
          : dataList[currentIndex];
    }
  }

  void changeAsset(int index) {
    currentIndex = index;
    currentAssetModel = dataList[index];
    notifyListeners();
  }

  void complete(BuildContext context) {
    // List<AssetEntity> temps = [];
    // for (var entity in selectedAssets) {
    //   temps.add(entity.assetEntity);
    // }
    // _selectedCallback?.call(temps);
    // _selectedCallback?.call(selectedAssets);
    Navigator.pop(context, selectedAssets);
  }

  /// 选择资源
  void clickAsset(BuildContext context) {
    if (currentAssetModel.assetEntity.duration > _maxVideoLength) {
      // HudUtil.toast("视频最大支持$_videoLength秒");
      return;
    }
    // 判断是否超过最大数
    if (!currentAssetModel.isSelected &&
        selectedAssets.length == _maxAssetCount) {
      // HudUtil.toast("最多选择$_limit张");
      JhToast.showText(context, msg: '最多选择$_maxAssetCount张图片');
      return;
    }

    currentAssetModel.isSelected = !currentAssetModel.isSelected;
    if (currentAssetModel.isSelected) {
      selectedAssets.add(currentAssetModel);
    } else {
      selectedAssets.removeWhere(
          (e) => e.assetEntity.id == currentAssetModel.assetEntity.id);
    }
    notifyListeners();
  }

  /// 点击选中的资源
  void clickSelectedAsset(AssetModel selectedModel) {
    int page = dataList
        .indexWhere((e) => e.assetEntity.id == selectedModel.assetEntity.id);
    pageController.animateToPage(page,
        duration: const Duration(microseconds: 250), curve: Curves.linear);
  }
}
